package com.xjj.homework.w02;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class M0047PermutationsII {

    public List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> permuteUnique(int[] nums) {
        // 避免重复,先排序,然后重复的条件是上个值等于这个值且上个值未用到
        Arrays.sort(nums);
        dfs(0, nums, new boolean[nums.length], new ArrayList<>());
        return result;
    }

    private void dfs(int index, int[] nums, boolean[] used, List<Integer> tmp) {
        // System.out.println(tmp);
        // System.out.println(index);
        if (index == nums.length) {
            result.add(new ArrayList<Integer>(tmp));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            // 已经用了或者重复了
            if (used[i] || (i > 0 && !used[i - 1] && nums[i] == nums[i - 1])) {
                continue;
            } else {
                used[i] = true;
                tmp.add(nums[i]);
                // 注意这里千万别写成++了....不然本地的值改了对下个循环有影响
                dfs(index + 1, nums, used, tmp);
                tmp.remove(tmp.size() - 1);
                used[i] = false;
            }

        }
    }

}
